Popular Searches
Popular Course Categories
Popular Courses

File Upload

Advanced Selenium

File Upload in Selenium WebDriver

File Upload is a common browser automation requirement in Selenium testing. Many web applications provide file upload functionality for documents, images, resumes, profile pictures, reports, PDFs, CSV files, and other files.

Selenium WebDriver can automate file upload when the web application uses an HTML <input type="file"> element. The most common approach is to locate the file input element and use the sendKeys() method to provide the complete path of the file.

File upload automation is frequently used in Selenium test scenarios such as registration forms, job portals, document submission systems, profile management, e-commerce applications, support portals, and administrative applications.

Course Resource: Selenium Training | Register for Course Demo


1. What is File Upload?

File upload is the process of selecting a file from the local computer and submitting it to a web application through an upload control.

For example, an application may contain an upload field for selecting a profile image:

<input type="file" id="profileImage">

In Selenium, this element can normally be located and supplied with a file path using sendKeys().


2. Why is File Upload Important in Selenium?

File upload is important because many real-world web applications require users to upload files during different workflows.

  • Resume upload.
  • Profile picture upload.
  • Document submission.
  • PDF upload.
  • CSV or Excel upload.
  • Image upload.
  • Product image upload.
  • Identity document upload.
  • Support attachment upload.
  • Bulk data upload.
  • Importing configuration files.

Automating these workflows allows testers to validate that file selection, validation, submission, and error handling work correctly.


3. Basic File Upload Flow

The basic Selenium file upload process can be represented as:

Open Application

        |

        v

Navigate to Upload Page

        |

        v

Locate <input type="file">

        |

        v

Use sendKeys()

        |

        v

Provide Absolute File Path

        |

        v

File Selected

        |

        v

Click Upload / Submit

        |

        v

Validate Upload Result


4. HTML File Upload Element

Understanding the HTML structure is important before automating a file upload.

<label for="fileUpload">Choose File</label>

<input type="file" id="fileUpload">

The important element is the input element with type="file".

Selenium can interact directly with this element when it is available and accessible in the DOM.


5. Using sendKeys() for File Upload

The most common Selenium approach is to locate the file input and use sendKeys() with the file path.

WebElement upload = driver.findElement(By.id("fileUpload"));

upload.sendKeys("C:\\Users\\User\\Documents\\resume.pdf");

Unlike normal text input, the value supplied to sendKeys() represents the local file path that should be selected for upload.


6. Complete Basic File Upload Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class FileUploadTest {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com/upload");

 

        driver.findElement(By.id("fileUpload"))

                .sendKeys("C:\\Users\\User\\Documents\\resume.pdf");

 

        driver.findElement(By.id("uploadButton"))

                .click();

 

        driver.quit();

    }

}

The script performs the following operations:

  1. Starts the browser.
  2. Opens the upload page.
  3. Locates the file input.
  4. Provides the file path.
  5. Clicks the upload button.
  6. Closes the browser.


7. File Upload Using ID Locator

If the file input has a unique ID, the ID locator is a simple and readable approach.

driver.findElement(By.id("fileUpload"))

        .sendKeys("C:\\TestData\\sample.pdf");

ID locators are generally easy to maintain when the application provides stable IDs.


8. File Upload Using Name Locator

If the upload element contains a unique name attribute, Selenium can locate it using By.name().

<input type="file" name="documentUpload">

driver.findElement(By.name("documentUpload"))

        .sendKeys("C:\\TestData\\document.pdf");


9. File Upload Using CSS Selector

CSS selectors can be used when an appropriate ID or name locator is unavailable.

driver.findElement(By.cssSelector("input[type='file']"))

        .sendKeys("C:\\TestData\\image.png");

If multiple file inputs exist, a more specific CSS selector should be used.

driver.findElement(

        By.cssSelector("input[type='file'][id='profileImage']")

).sendKeys("C:\\TestData\\profile.png");


10. File Upload Using XPath

XPath can also be used to identify a file input.

driver.findElement(By.xpath("//input[@type='file']"))

        .sendKeys("C:\\TestData\\document.pdf");

A more specific XPath can be used when several upload controls are present.

driver.findElement(

        By.xpath("//input[@type='file' and @id='resume']")

).sendKeys("C:\\TestData\\resume.pdf");


11. Absolute File Path

An absolute file path specifies the complete location of a file on the computer.

C:\Users\User\Documents\TestData\resume.pdf

In Java strings, Windows backslashes need to be escaped.

String filePath = "C:\\Users\\User\\Documents\\TestData\\resume.pdf";

An absolute path is straightforward for local execution, but hard-coding machine-specific paths can reduce framework portability.


12. Relative File Path

A relative path is specified relative to the project's working directory.

test-data/resume.pdf

Using project-relative test data can make an automation framework easier to share across different machines.

String filePath = "test-data/resume.pdf";

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(filePath);


13. Using System.getProperty("user.dir")

A common approach for creating a portable path is to obtain the current project directory using System.getProperty("user.dir").

String projectPath = System.getProperty("user.dir");

 

String filePath = projectPath

        + "\\test-data\\resume.pdf";

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(filePath);

This avoids depending directly on a specific user's home directory.


14. File Upload with Path

Modern Java applications can use the Path and Paths classes to construct file paths.

import java.nio.file.Path;

import java.nio.file.Paths;

 

Path filePath = Paths.get(

        System.getProperty("user.dir"),

        "test-data",

        "resume.pdf"

);

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(filePath.toString());

This approach is useful for building cleaner and more maintainable test-data paths.


15. File Upload with File Class

The Java File class can also be used to work with file paths.

import java.io.File;

 

File file = new File(

        "test-data/resume.pdf"

);

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(file.getAbsolutePath());

This approach converts a project-relative path into an absolute path before passing it to Selenium.


16. Verifying File Existence Before Upload

Before uploading a file, it is useful to verify that the file actually exists.

import java.io.File;

 

File file = new File("test-data/resume.pdf");

 

if (!file.exists()) {

    throw new RuntimeException(

        "File not found: " + file.getAbsolutePath()

    );

}

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(file.getAbsolutePath());

This prevents confusing Selenium failures caused by incorrect test-data paths.


17. Verifying That the Path Represents a File

A path may exist but point to a directory instead of a file. Therefore, a framework can verify both existence and file type.

File file = new File("test-data/resume.pdf");

 

if (!file.exists() || !file.isFile()) {

    throw new RuntimeException(

        "Invalid upload file: " + file.getAbsolutePath()

    );

}

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(file.getAbsolutePath());


18. Uploading an Image

Image upload is common in profile, product, social media, and content management applications.

String imagePath =

        System.getProperty("user.dir")

        + "\\test-data\\profile.png";

 

driver.findElement(By.id("profileImage"))

        .sendKeys(imagePath);

 

driver.findElement(By.id("saveButton"))

        .click();


19. Uploading a PDF

PDF files are frequently uploaded for resumes, invoices, certificates, reports, and supporting documents.

String pdfPath =

        System.getProperty("user.dir")

        + "\\test-data\\document.pdf";

 

driver.findElement(By.id("document"))

        .sendKeys(pdfPath);

 

driver.findElement(By.id("upload"))

        .click();


20. Uploading an Excel File

Applications that support bulk data imports may allow users to upload Excel files.

String excelPath =

        System.getProperty("user.dir")

        + "\\test-data\\users.xlsx";

 

driver.findElement(By.id("excelUpload"))

        .sendKeys(excelPath);

 

driver.findElement(By.id("importButton"))

        .click();


21. Uploading a CSV File

CSV files are commonly used for bulk data import and migration testing.

String csvPath =

        System.getProperty("user.dir")

        + "\\test-data\\users.csv";

 

driver.findElement(By.id("csvUpload"))

        .sendKeys(csvPath);

 

driver.findElement(By.id("uploadButton"))

        .click();


22. Uploading Multiple Files

If an application supports multiple file selection through a single file input, Selenium can provide multiple paths separated by newline characters.

String file1 =

        System.getProperty("user.dir")

        + "\\test-data\\document1.pdf";

 

String file2 =

        System.getProperty("user.dir")

        + "\\test-data\\document2.pdf";

 

String files = file1 + "\n" + file2;

 

driver.findElement(By.id("documents"))

        .sendKeys(files);

This technique depends on the application's file input supporting multiple file selection.


23. HTML Multiple File Upload

An HTML multiple upload control may look like this:

<input type="file" id="documents" multiple>

The multiple attribute allows the control to accept more than one file.


24. Verifying Multiple File Selection

After selecting multiple files, the application may display the selected file names. Selenium can verify the displayed information.

String expectedFile = "document1.pdf";

 

String uploadedFileName =

        driver.findElement(

            By.id("selectedFileName")

        ).getText();

 

Assert.assertTrue(

        uploadedFileName.contains(expectedFile)

);


25. File Upload with TestNG

File upload can be integrated with TestNG to create structured automated tests.

import java.io.File;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class FileUploadTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

        driver.get("https://example.com/upload");

    }

 

    @Test

    public void uploadFileTest() {

 

        File file =

                new File("test-data/resume.pdf");

 

        driver.findElement(By.id("fileUpload"))

                .sendKeys(file.getAbsolutePath());

 

        driver.findElement(By.id("uploadButton"))

                .click();

 

        String message =

                driver.findElement(By.id("successMessage"))

                        .getText();

 

        Assert.assertTrue(

                message.contains("success")

        );

    }

 

    @AfterMethod

    public void tearDown() {

        if (driver != null) {

            driver.quit();

        }

    }

}


26. File Upload with Page Object Model

File upload can be separated into a Page Object method while the test class remains responsible for test execution and validation.

public class UploadPage {

 

    WebDriver driver;

 

    By fileInput = By.id("fileUpload");

    By uploadButton = By.id("uploadButton");

    By successMessage = By.id("successMessage");

 

    public UploadPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void uploadFile(String filePath) {

        driver.findElement(fileInput)

                .sendKeys(filePath);

    }

 

    public void clickUpload() {

        driver.findElement(uploadButton)

                .click();

    }

 

    public String getSuccessMessage() {

        return driver.findElement(successMessage)

                .getText();

    }

}


27. POM Test Class for File Upload

public class UploadTest {

 

    WebDriver driver;

    UploadPage uploadPage;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

        driver.get("https://example.com/upload");

        uploadPage = new UploadPage(driver);

    }

 

    @Test

    public void uploadTest() {

 

        String filePath =

                System.getProperty("user.dir")

                + "\\test-data\\resume.pdf";

 

        uploadPage.uploadFile(filePath);

        uploadPage.clickUpload();

 

        Assert.assertTrue(

                uploadPage.getSuccessMessage()

                        .contains("success")

        );

    }

 

    @AfterMethod

    public void tearDown() {

        driver.quit();

    }

}


28. File Upload Using Data Provider

TestNG Data Providers can be used to test multiple files with the same upload workflow.

@DataProvider(name = "files")

public Object[][] files() {

    return new Object[][] {

        {"test-data/resume.pdf"},

        {"test-data/profile.png"},

        {"test-data/document.pdf"}

    };

}

 

@Test(dataProvider = "files")

public void uploadTest(String filePath) {

 

    File file = new File(filePath);

 

    driver.findElement(By.id("fileUpload"))

            .sendKeys(file.getAbsolutePath());

 

    driver.findElement(By.id("uploadButton"))

            .click();

}


29. File Upload with Expected Results

A Data Provider can supply both the file path and expected result.

@DataProvider(name = "uploadData")

public Object[][] uploadData() {

    return new Object[][] {

        {"test-data/resume.pdf", "success"},

        {"test-data/image.png", "success"},

        {"test-data/document.txt", "invalid"}

    };

}

 

@Test(dataProvider = "uploadData")

public void uploadValidationTest(

        String filePath,

        String expectedResult) {

 

    File file = new File(filePath);

 

    driver.findElement(By.id("fileUpload"))

            .sendKeys(file.getAbsolutePath());

 

    driver.findElement(By.id("uploadButton"))

            .click();

 

    String actualResult =

            driver.findElement(By.id("message"))

                    .getText();

 

    Assert.assertTrue(

            actualResult.toLowerCase()

                    .contains(expectedResult)

    );

}


30. File Type Validation

Many applications restrict uploads to specific file types. For example, a resume portal may allow PDF and DOCX files but reject executable files.

File TypeExamplePossible Validation
PDFresume.pdfAllowed
DOCXresume.docxAllowed
PNGprofile.pngAllowed for image upload
JPGphoto.jpgAllowed for image upload
TXTnotes.txtMay be rejected
EXEprogram.exeUsually restricted


31. Testing Invalid File Types

Negative testing should verify that unsupported file types are rejected correctly.

String invalidFile =

        System.getProperty("user.dir")

        + "\\test-data\\invalid.exe";

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(invalidFile);

 

driver.findElement(By.id("uploadButton"))

        .click();

 

String error =

        driver.findElement(By.id("errorMessage"))

                .getText();

 

Assert.assertTrue(

        error.contains("file type")

);


32. Testing File Size Validation

Applications may impose maximum file-size restrictions.

For example, a website may allow files up to a specific configured size.

File file = new File(

        "test-data/large-file.pdf"

);

 

System.out.println(

        "File size: " + file.length()

);

The test can then upload the file and verify that the application displays the appropriate validation message.


33. Testing Empty File Upload

A file upload field may be mandatory. A test should verify the behavior when the user clicks the upload or submit button without selecting a file.

driver.findElement(By.id("uploadButton"))

        .click();

 

String error =

        driver.findElement(By.id("errorMessage"))

                .getText();

 

Assert.assertTrue(

        error.contains("required")

);


34. Testing File Name Validation

Some applications validate file names or file extensions. Test cases can include valid and invalid file names.

Test CaseFile NameExpected Result
Valid PDFresume.pdfAccepted
Valid DOCXresume.docxAccepted
Wrong Extensionresume.exeRejected
Empty Namefile without valid nameValidation
Long NameVery long file nameApplication-specific validation


35. Handling File Upload Success Messages

After uploading a file, the application may display a success message.

String message =

        driver.findElement(

            By.id("successMessage")

        ).getText();

 

Assert.assertTrue(

        message.contains("File uploaded")

);


36. Handling File Upload Error Messages

Invalid files should normally produce an error or validation message.

String errorMessage =

        driver.findElement(

            By.id("errorMessage")

        ).getText();

 

Assert.assertTrue(

        errorMessage.contains("Invalid file")

);


37. Waiting for Upload Completion

File upload may involve server-side processing. In such situations, an explicit wait can be used to wait for a success message or another upload-completion indicator.

WebDriverWait wait =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );

 

WebElement message =

        wait.until(

            ExpectedConditions.visibilityOfElementLocated(

                By.id("successMessage")

            )

        );

 

Assert.assertTrue(

        message.isDisplayed()

);


38. Waiting for Upload Button

If the upload button becomes available after file selection, Selenium can wait for it to become clickable.

WebDriverWait wait =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );

 

WebElement uploadButton =

        wait.until(

            ExpectedConditions.elementToBeClickable(

                By.id("uploadButton")

            )

        );

 

uploadButton.click();


39. File Upload with Hidden Input

Some modern web applications hide the native file input and display a custom upload button.

For example:

<button id="chooseFile">Upload File</button>

<input type="file" id="fileInput" style="display:none">

The visible button may trigger the hidden file input through JavaScript.

When possible, the automation should interact with the actual file input rather than attempting to automate the operating-system file dialog.


40. Why sendKeys() is Preferred for File Input

When the application exposes a standard HTML file input, sendKeys() is generally simpler and more reliable than automating the operating-system file-selection window.

  • It works directly with the HTML file input.
  • It avoids OS-specific file-dialog interactions.
  • It is easier to integrate into CI environments.
  • It is suitable for automated test frameworks.
  • It keeps the automation logic inside Selenium.


41. Native File Dialog Problem

A common misconception is that Selenium directly controls every operating-system window. Selenium primarily automates the browser and web page.

A native file chooser can appear when a user clicks a file-upload control. Instead of trying to control that dialog, the preferred Selenium approach for a standard file input is usually:

driver.findElement(By.id("fileInput"))

        .sendKeys(filePath);


42. Selenium File Upload vs OS File Dialog

ApproachDescription
sendKeys()Provides a file path directly to an HTML file input.
OS AutomationAutomates the native operating-system file chooser.
JavaScriptMay be used for special application behavior, but should not be used to bypass application security.

For a standard Selenium file input, sendKeys() is normally the simplest approach.


43. File Upload with JavaScript-Triggered Input

Some applications use JavaScript to trigger the file input when the user clicks a custom button.

The automation should identify the underlying file input in the DOM and use it where possible.

WebElement fileInput =

        driver.findElement(

            By.cssSelector("input[type='file']")

        );

 

fileInput.sendKeys(

        new File("test-data/document.pdf")

                .getAbsolutePath()

);


44. Handling Multiple Upload Controls

If a page contains several upload controls, a generic locator such as input[type='file'] may return multiple elements.

Use a specific locator.

driver.findElement(

        By.id("resumeUpload")

).sendKeys(

        new File("test-data/resume.pdf")

                .getAbsolutePath()

);

 

driver.findElement(

        By.id("profileUpload")

).sendKeys(

        new File("test-data/profile.png")

                .getAbsolutePath()

);


45. File Upload Using WebElement

Storing the upload element in a WebElement variable can make the code easier to read.

WebElement fileInput =

        driver.findElement(By.id("fileUpload"));

 

String filePath =

        new File("test-data/document.pdf")

                .getAbsolutePath();

 

fileInput.sendKeys(filePath);


46. Creating a Reusable Upload Utility

Large Selenium frameworks can create reusable utility methods for file uploads.

public class FileUploadUtil {

 

    public static void uploadFile(

            WebDriver driver,

            By locator,

            String filePath) {

 

        File file = new File(filePath);

 

        if (!file.exists()) {

            throw new RuntimeException(

                "File not found: "

                + file.getAbsolutePath()

            );

        }

 

        driver.findElement(locator)

                .sendKeys(file.getAbsolutePath());

    }

}

The utility can then be reused across multiple tests.


47. Using the File Upload Utility

FileUploadUtil.uploadFile(

        driver,

        By.id("fileUpload"),

        "test-data/resume.pdf"

);

 

driver.findElement(By.id("uploadButton"))

        .click();


48. File Upload Utility with Path

public static String getFilePath(String fileName) {

 

    return Paths.get(

        System.getProperty("user.dir"),

        "test-data",

        fileName

    ).toString();

}

Usage:

String path =

        FileUploadUtil.getFilePath("resume.pdf");

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(path);


49. File Upload and Page Object Model Architecture

Test Class

    |

    v

Page Object

    |

    v

Upload Method

    |

    v

File Path Utility

    |

    v

Local Test Data

    |

    v

HTML File Input

    |

    v

Upload Button

    |

    v

Application

    |

    v

Validation / Assertion


50. File Upload Project Structure

src

|-- test

|   |-- java

|   |   |-- tests

|   |   |   |-- FileUploadTest.java

|   |   |

|   |   |-- pages

|   |   |   |-- UploadPage.java

|   |   |

|   |   |-- utilities

|   |       |-- FileUploadUtil.java

|   |       |-- DriverFactory.java

|   |

|-- test-data

|   |-- resume.pdf

|   |-- profile.png

|   |-- document.pdf

|   |-- users.csv

|   |-- users.xlsx

|   |

|-- pom.xml


51. File Upload with External Test Data

File names can be stored separately from test logic and passed into the test through a Data Provider or configuration mechanism.

@DataProvider(name = "uploadFiles")

public Object[][] uploadFiles() {

    return new Object[][] {

        {"resume.pdf"},

        {"profile.png"},

        {"document.pdf"}

    };

}

 

@Test(dataProvider = "uploadFiles")

public void uploadTest(String fileName) {

 

    String filePath = Paths.get(

        System.getProperty("user.dir"),

        "test-data",

        fileName

    ).toString();

 

    driver.findElement(By.id("fileUpload"))

            .sendKeys(filePath);

}


52. File Upload Test Scenarios

ScenarioExpected Result
Valid PDFFile uploaded successfully
Valid imageImage uploaded successfully
Unsupported extensionValidation error
Large fileSize validation message
No file selectedRequired-field validation
Multiple filesFiles accepted when supported
Duplicate fileApplication-specific behavior
Invalid file nameValidation message when applicable


53. Positive File Upload Testing

Positive test cases verify that supported files can be uploaded successfully.

  • Upload a valid PDF.
  • Upload a valid PNG image.
  • Upload a valid JPG image.
  • Upload a valid DOCX document.
  • Upload a file within the allowed size.
  • Upload multiple files when supported.
  • Verify the success message.
  • Verify the uploaded file name.


54. Negative File Upload Testing

Negative test cases verify that invalid uploads are handled correctly.

  • Upload an unsupported file type.
  • Upload an oversized file.
  • Submit without selecting a file.
  • Use an invalid file name.
  • Use a corrupted test file when appropriate.
  • Verify the correct validation message.
  • Verify that invalid files are not accepted as successful uploads.


55. File Upload Validation Matrix

InputExpected Behavior
resume.pdfAccepted
resume.docxAccepted if DOCX is supported
photo.pngAccepted for image upload
script.exeRejected
very-large.pdfRejected if above size limit
No fileRequired validation


56. File Upload and Security Testing

File upload functionality can introduce security risks if the application does not validate uploaded content correctly. Automation tests can verify expected application-side validation behavior.

Typical validation areas include:

  • Allowed file extensions.
  • Maximum file size.
  • Required file validation.
  • File-name validation.
  • Duplicate-file handling.
  • Application response to malformed test files.
  • Authentication and authorization requirements.

Security testing should be performed according to the application's authorized testing scope and security requirements.


57. File Upload in CI/CD

File upload tests should work reliably in CI/CD environments. Test files should preferably be maintained as project test data or retrieved through an approved test-data mechanism rather than relying on a developer's personal desktop path.

Developer Commit

       |

       v

CI/CD Pipeline

       |

       v

Build

       |

       v

TestNG

       |

       v

File Upload Test

       |

       v

Test Data

       |

       v

Selenium WebDriver

       |

       v

Application

       |

       v

Assertions

       |

       v

Test Report


58. Avoiding Machine-Specific Paths

Avoid hard-coded paths such as:

C:\Users\John\Desktop\resume.pdf

Instead, use project-relative or dynamically constructed paths.

String filePath = Paths.get(

        System.getProperty("user.dir"),

        "test-data",

        "resume.pdf"

).toString();

This makes the test easier to execute on different development and CI machines.


59. Cross-Platform File Paths

Using Paths.get() is useful when a framework needs to run on different operating systems.

Path path = Paths.get(

        System.getProperty("user.dir"),

        "test-data",

        "resume.pdf"

);

 

String filePath = path.toString();

This avoids manually constructing operating-system-specific separators.


60. File Upload with Assertions

Uploading the file is only one part of the test. The test should verify that the application processed the file correctly.

driver.findElement(By.id("fileUpload"))

        .sendKeys(filePath);

 

driver.findElement(By.id("uploadButton"))

        .click();

 

WebElement successMessage =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        ).until(

            ExpectedConditions.visibilityOfElementLocated(

                By.id("successMessage")

            )

        );

 

Assert.assertTrue(

        successMessage.getText()

                .contains("uploaded")

);


61. File Upload and Test Reports

File upload tests should provide useful information in automation reports. When a test fails, the report should make it possible to identify the file and scenario being tested without exposing sensitive information.

Test Case: Resume Upload

File: resume.pdf

Expected: Upload Successful

Actual: Upload Successful

Status: PASS

For failures, useful information may include the test scenario, file name, validation message, and screenshot or browser evidence where the framework supports it.


62. Common Mistakes in File Upload

  • Using an incorrect file path.
  • Using a file that does not exist.
  • Using the wrong locator.
  • Trying to use sendKeys() on a non-file element.
  • Assuming every custom upload button is itself an input element.
  • Ignoring hidden or dynamically generated file inputs.
  • Using machine-specific paths.
  • Not verifying the uploaded result.
  • Not waiting for asynchronous upload completion.
  • Sharing mutable test files across parallel tests without proper isolation.
  • Hard-coding test data in multiple test classes.
  • Not testing invalid file types and file-size boundaries.


63. Common Error: File Not Found

If the specified path does not point to a real file, the upload test will fail.

Use Java file validation before calling sendKeys().

File file = new File(filePath);

 

if (!file.exists()) {

    throw new RuntimeException(

        "File does not exist: "

        + file.getAbsolutePath()

    );

}


64. Common Error: Wrong Locator

If the locator points to a button, label, or another element instead of the actual file input, the upload operation may fail.

Inspect the HTML and identify:

<input type="file">

Then locate that element.

driver.findElement(

        By.cssSelector("input[type='file']")

).sendKeys(filePath);


65. Common Error: File Input Not Present

Some applications create the file input dynamically only after a user interaction. In such cases, the automation may need to trigger the appropriate page action and then locate the input.

driver.findElement(By.id("chooseFile"))

        .click();

 

WebElement fileInput =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        ).until(

            ExpectedConditions.presenceOfElementLocated(

                By.cssSelector("input[type='file']")

            )

        );

 

fileInput.sendKeys(filePath);


66. Common Error: Upload Completion Not Verified

A test should not assume that selecting a file means the server successfully received it.

A complete test should generally validate an application-specific result such as:

  • Success message.
  • Uploaded file name.
  • Preview.
  • Updated record.
  • Downloadable uploaded document.
  • Changed application state.


67. Best Practices for File Upload Automation

  • Prefer sendKeys() for standard HTML file inputs.
  • Keep test files inside a dedicated test-data directory.
  • Use relative or dynamically constructed paths.
  • Validate that files exist before uploading.
  • Use Page Object Model for application interaction logic.
  • Create reusable file-upload utilities.
  • Use Data Providers for multiple upload scenarios.
  • Test both valid and invalid files.
  • Validate file-size restrictions.
  • Validate file-type restrictions.
  • Use explicit waits for asynchronous upload completion.
  • Do not expose passwords, tokens, or other secrets in uploaded test data.
  • Ensure test files are available in CI/CD environments.
  • Keep parallel tests isolated when they modify uploaded files.
  • Capture useful failure information in reports.


68. File Upload Framework Architecture

                Test Class

                    |

                    v

             Data Provider

                    |

                    v

             Upload Page

                    |

                    v

          File Upload Utility

                    |

                    v

              Test Data

                    |

                    v

             File Input

                    |

                    v

            Upload Button

                    |

                    v

              Application

                    |

                    v

               Assertion

                    |

                    v

                Report


69. Complete Practical File Upload Example

import java.io.File;

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

 

public class FileUploadTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

 

        driver = new ChromeDriver();

 

        driver.manage().window().maximize();

 

        driver.get(

            "https://example.com/upload"

        );

    }

 

    @DataProvider(name = "uploadData")

    public Object[][] uploadData() {

 

        return new Object[][] {

            {"resume.pdf"},

            {"document.pdf"},

            {"profile.png"}

        };

    }

 

    @Test(dataProvider = "uploadData")

    public void uploadFileTest(String fileName) {

 

        String filePath = new File(

            "test-data/" + fileName

        ).getAbsolutePath();

 

        File file = new File(filePath);

 

        Assert.assertTrue(

            file.exists(),

            "File not found: " + filePath

        );

 

        driver.findElement(

            By.id("fileUpload")

        ).sendKeys(filePath);

 

        driver.findElement(

            By.id("uploadButton")

        ).click();

 

        WebDriverWait wait =

            new WebDriverWait(

                driver,

                Duration.ofSeconds(10)

            );

 

        String message =

            wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.id("successMessage")

                )

            ).getText();

 

        Assert.assertTrue(

            message.toLowerCase()

                   .contains("uploaded")

        );

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}


70. Practical File Upload Project

Consider a job portal that allows users to upload resumes.

The automation framework can validate the complete workflow:

Open Job Portal

      |

      v

Login

      |

      v

Open Profile

      |

      v

Select Resume Upload

      |

      v

Locate File Input

      |

      v

Upload resume.pdf

      |

      v

Click Save

      |

      v

Wait for Upload

      |

      v

Verify Success Message

      |

      v

Verify Resume Name

      |

      v

Generate Test Report

Additional negative scenarios can include unsupported file types, oversized files, missing files, and invalid file names.


71. Real-World File Upload Test Cases

Test CaseInputExpected Result
Valid Resumeresume.pdfUpload successful
Valid Documentdocument.docxUpload successful if supported
Valid Imageprofile.pngUpload successful
Invalid Extensionprogram.exeValidation error
Large Filelarge.pdfSize validation
No FileNo selectionRequired validation
Multiple FilesSeveral supported filesAccepted when supported
Incorrect File NameInvalid naming scenarioValidation when applicable
Upload FailureTest failure conditionCorrect error displayed


72. File Upload vs File Download

FeatureFile UploadFile Download
DirectionLocal system to applicationApplication to local system
Common Elementinput type="file"Download link/button
Typical Selenium ActionsendKeys(filePath)Click download element
ValidationUploaded file/resultDownloaded file existence/content


73. File Upload vs sendKeys for Text Input

AspectText InputFile Input
PurposeEnter textSelect file for upload
MethodsendKeys("text")sendKeys("file path")
ExampleUsernameresume.pdf
ValidationEntered textUploaded file/result


74. Quick Revision

  • File upload is commonly automated using the HTML file input.
  • The standard Selenium technique is sendKeys().
  • Provide the complete file path to sendKeys().
  • Use File or Path to construct reliable paths.
  • System.getProperty("user.dir") can help create project-relative paths.
  • Always verify that the test file exists.
  • Use POM to keep upload interactions maintainable.
  • Use Data Providers for multiple files or upload scenarios.
  • Use explicit waits when upload completion is asynchronous.
  • Validate both positive and negative file-upload scenarios.
  • Avoid machine-specific file paths.
  • Make test files available in CI/CD environments.
  • Verify the actual application result after upload.


75. Interview Questions on File Upload

1. How do you upload a file using Selenium?

For a standard HTML file input, locate the input element and use sendKeys() with the file path.

2. Which HTML element is commonly used for file upload?

The standard element is <input type="file">.

3. Can Selenium handle a file upload without opening the native file dialog?

Yes. When a standard file input is available, sendKeys() can provide the file path directly to the element.

4. Why is sendKeys() used for file upload?

It allows Selenium to provide the local file path directly to the HTML file input.

5. Can XPath be used for file upload?

Yes. XPath can locate an input element with type="file".

6. Can CSS selectors be used for file upload?

Yes. For example, input[type='file'] can locate a standard file input.

7. How can you create a portable file path?

Use project-relative paths, System.getProperty("user.dir"), or Java Path APIs instead of hard-coded personal computer paths.

8. How do you verify that the file exists?

Use Java's File or Path APIs before passing the path to Selenium.

9. Can Selenium upload multiple files?

Yes, when the application supports multiple selection. Multiple paths can be supplied to the file input using newline-separated paths.

10. How do you test an invalid file type?

Upload a controlled test file with an unsupported extension and verify that the application displays the expected validation.

11. How do you test file-size validation?

Use test files representing valid and oversized conditions and verify the application's response.

12. Can File Upload be integrated with TestNG?

Yes. File upload tests can use TestNG annotations, assertions, Data Providers, configuration methods, and reports.

13. Can File Upload be implemented using Page Object Model?

Yes. The upload locator and upload actions can be encapsulated inside a Page Object.

14. How do you handle a hidden file input?

When possible, locate the underlying HTML file input and provide the file path directly rather than automating the operating-system file dialog.

15. Why should hard-coded local paths be avoided?

They make tests dependent on one particular machine and can cause failures on other developer machines or CI environments.

16. How can file upload tests run in CI/CD?

Keep required test files in the project or an approved test-data source and construct paths dynamically so the files are available in the CI environment.

17. How do you verify successful file upload?

Verify an application-specific success message, uploaded file name, preview, updated record, or another reliable result.

18. Can Data Providers be used for file upload?

Yes. A Data Provider can provide multiple file names, paths, expected results, or upload scenarios.

19. What are common file-upload mistakes?

Incorrect file paths, wrong locators, missing files, unsupported file types, failure to wait for upload completion, and failure to verify the result are common mistakes.

20. What is the preferred approach for a standard HTML file input?

Locate the file input and use sendKeys() with the appropriate file path.


76. Learning Roadmap for File Upload

  1. Understand HTML file input elements.
  2. Learn Selenium locators.
  3. Learn sendKeys() for file inputs.
  4. Practice absolute file paths.
  5. Practice project-relative file paths.
  6. Learn Java File and Path APIs.
  7. Validate file existence.
  8. Automate PDF and image uploads.
  9. Automate multiple file uploads.
  10. Test invalid file extensions.
  11. Test file-size validation.
  12. Use explicit waits for upload completion.
  13. Integrate file upload with TestNG.
  14. Integrate file upload with Data Providers.
  15. Implement file upload in Page Object Model.
  16. Create reusable file-upload utilities.
  17. Run upload tests in CI/CD.
  18. Integrate upload tests with reporting.


77. Summary

File Upload is an important Selenium WebDriver automation concept used to automate web applications that accept documents, images, spreadsheets, PDFs, and other files.

For a standard HTML <input type="file"> element, the most common Selenium approach is to locate the element and use sendKeys() with the appropriate file path.

A reliable automation framework should avoid machine-specific paths, verify file existence, organize test files properly, validate upload results, handle asynchronous upload operations, and include both positive and negative test cases.

File upload automation becomes more maintainable when combined with TestNG, Data Providers, Page Object Model, reusable utilities, assertions, explicit waits, and reporting.

Final Takeaway: A robust Selenium file-upload test does more than select a file. It validates the complete upload workflow, including file selection, file-type and size validation, upload processing, success or error messages, and the final application state.


78. Course Resources

Learn more about Selenium automation testing and related framework concepts:

whatsapp